<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加角色对话框      重点   取消的操作-->
    <el-dialog
      title="添加角色"
      :visible.sync="rolesadd"
      width="30%"
      @close="rolesreset"
    >
      <span>
        <el-form
          :model="rolesrF"
          :rules="rolesrFrules"
          ref="rolesrFref"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesrF.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesrF.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesadd = false">取 消</el-button>
        <el-button type="primary" @click="tjxinxi">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="xianshibj"
      width="30%"
      @close="rolesClose"
    >
      <span>
        <el-form
          :model="roleslistbj"
          :rules="rulesFormbjrules"
          ref="roleslistbjref"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleslistbj.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="roleslistbj.roleDesc"></el-input>
          </el-form-item> </el-form
      ></span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="xianshibj = false">取 消</el-button>
        <el-button type="primary" @click="rolesqryj()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="fenQian"
      width="50%"
      @close="setDialogclose"
    >
      <el-tree
        default-expand-all
        :data="quanxianlist"
        :props="treeProp"
        show-checkbox
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="fenQian = false">取 消</el-button>
        <el-button type="primary" @click="allRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 卡片试图 -->
    <el-card class="roles-box">
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" class="add-box" @click="addjiaose"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色区域   -->
      <el-table border :data="roleslist" class="rolestable" stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <!-- {{scope.row}} -->
            <el-row
              :class="['vcenter']"
              v-for="item1 in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removetag(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级 -->
              <el-col :span="19">
                <el-row
                  :class="['vcenter']"
                  v-for="item2 in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removetag(scope.row, item2.id)"
                      type="success"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removetag(scope.row, item3.id)"
                      >{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- {{ scope.row }} -->
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="rolesbj(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeroles(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="fenQianAn(scope.row)"
                >分配权限</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 树形数据
      treeProp: {
        children: "children",
        label: "authName",
      },
      // 获取权限的数据
      quanxianlist: [],
      // 分配权限
      fenQian: false,
      roleId: "",
      // 编辑角色 id
      roleslistbj: {},
      // 编辑角色

      // 存储角色列表
      roleslist: [],
      //   添加角色显示与隐藏
      rolesadd: false,
      //   编辑角色显示与隐藏
      xianshibj: false,
      // 当前即将分配权限的角色id
      roleIds: "",
      rolesrF: {
        // 角色名称
        roleName: "",
        // 角色描述
        roleDesc: "",
      },
      // 默认选中的节点id值数组
      defKeys: [],
      //   校验用户规则
      rolesrFrules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
      rulesFormbjrules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getroleslist();
  },
  methods: {
    async getroleslist() {
      const { data: res } = await this.$http.get("roles");
      //   console.log("22222", res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      } else {
        this.roleslist = res.data;
      }
    },
    // 添加角色
    addjiaose() {
      this.rolesadd = true;
    },
    //    监听取消
    rolesreset() {
      this.$refs.rolesrFref.resetFields();
    },
    // 提交角色
    tjxinxi() {
      this.$refs.rolesrFref.validate(async (valid) => {
        if (!valid) return;
        // console.log('8989',valid)
        const { data: res } = await this.$http.post("roles", this.rolesrF);
        console.log("0202", res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加角色失败");
        } else {
          this.$message.success("添加角色成功");
          this.rolesadd = false;
          // 刷新数据
          this.getroleslist();
        }
      });
    },
    // 编辑角色
    async rolesbj(id) {
      this.xianshibj = true;
      this.roleId = id;
      // 根据id查询角色
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("请求数据失败");
      } else {
        // 不懂
        this.roleslistbj = res.data;
        console.log("获取到的数据", res.data);
      }
    },
    // 确认提交   编辑角色
    rolesqryj() {
      this.$refs.roleslistbjref.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.roleId,
          this.roleslistbj
          //   {
          //     roleId:this.roleId,
          //     roleName: this.roleslistbj.roleName,
          //     roleDesc: this.roleslistbj.roleDesc,
          //   }
        );
        console.log("确定", res);
        if (res.meta.status !== 200) {
          return this.$message.error("更新失败");
        } else {
          this.xianshibj = false;
          this.$message.success("更新成功");
          // 刷新数据
          console.log(111);

          this.getroleslist();
        }
      });
    },
    // 重置
    rolesClose() {
      this.$refs.roleslistbjref.resetFields();
    },
    // 删除角色
    async removeroles(id) {
      const rolesremove = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      console.log("333333", rolesremove);
      //   确定     confirm    取消   cancel
      if (rolesremove !== "confirm") {
        return this.$message.info("取消删除");
      } else {
        const { data: res } = await this.$http.delete("roles/" + id);
        console.log("213465", res);
        if (res.meta.status !== 200) {
          return this.$message.error("删除用户失败");
        } else {
          // 刷新数据
          this.getroleslist();
          this.$message.success("删除用户成功");
        }
      }
    },
    async removetag(rolesId, rightId) {
      const tagre = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      console.log("22222", tagre);
      if (tagre !== "confirm") {
        return this.$message.info("取消删除");
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${rolesId.id}/rights/${rightId}`
        );
        console.log("确认删除", res);
        if (res.meta.status !== 200) {
          return this.message.error("删除权限失败");
        } else {
          // 刷新数据
          rolesId.children = res.data;
        }
      }
    },
    // 分配权限按钮
    async fenQianAn(role) {
      this.roleIds = role.id;
      this.fenQian = true;
      const { data: res } = await this.$http.get("rights/tree");
      console.log("15896", res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限失败");
      } else {
        this.quanxianlist = res.data;
      }
      // 递归获取三级节点的id
      this.getdidui(role, this.defKeys);
    },

    // 太难    重点
    // 通过递归的形式,获取角色所有三级权限的id 并保存到deyKeys 数组中
    getdidui(node, arr) {
      // 如果当前node 节点不包括 children 属性   则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => this.getdidui(item, arr));
    },
    // 监听分配权限对话框的关闭事件
    setDialogclose() {
      this.defKeys = [];
    },

    // 重点      重点      重点
    // 点击为角色分配权限
    async allRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // console.log('88888',keys)
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleIds}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      } else {
        this.$message.success("分配权限成功");
        this.getroleslist();
        this.fenQian = false;
      }
    },
  },
  //
};
</script>

<style lang="less" scoped>
.roles-box {
  margin-top: 15px;
}
.rolestable {
  margin-top: 15px;
}
.rolestag {
  margin-left: 50px;
  // margin: 7px;
  margin-top: 10px;
}
.el-tag {
  margin: 7px;
  margin-left: 50px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>